<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { BasicOption } from '@vben/types';

import { computed, h, onMounted, ref } from 'vue';

import { AuthenticationLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { Input as VbenInput } from '@vben-core/shadcn-ui';

import { Apis } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

const MOCK_USER_OPTIONS: BasicOption[] = [
  {
    label: '超级管理员',
    value: 'vben',
  },
  {
    label: '管理员',
    value: 'admin',
  },
  {
    label: '用户',
    value: 'jack',
  },
];

const captchaInfo = ref({
  code: '',
  captchaEnabled: false,
  img: '',
  uuid: '',
});
const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        class: 'w-full',
        placeholder: $t('authentication.usernameTip'),
      },
      dependencies: {
        trigger(values, form) {
          if (values.selectAccount) {
            const findUser = MOCK_USER_OPTIONS.find(
              (item) => item.value === values.selectAccount,
            );
            if (findUser) {
              form.setValues({
                password: '123456',
                username: findUser.value,
              });
            }
          }
        },
        triggerFields: ['selectAccount'],
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    ...(captchaInfo.value.captchaEnabled
      ? [
          {
            fieldName: 'code',
            component: h('div', { class: 'flex items-center gap-2' }, [
              h(VbenInput, {
                placeholder: '',
                class: 'flex-1',
                modelValue: captchaInfo.value.code,
                onInput: (e) => (captchaInfo.value.code = e.target.value),
              }),
              h('img', {
                src: captchaInfo.value.img,
                alt: '验证码',
                class: 'h-8 w-24 cursor-pointer',
                onClick: getCaptchaImage,
              }),
            ]),
            componentProps: {
              placeholder: $t('authentication.code'),
            },
          },
        ]
      : []),
  ];
});

const isDev = import.meta.env.MODE === 'development';
function mockLogin(username: string, password: string, isSkip: boolean = true) {
  authStore.authLogin({
    username,
    password,
    _isSkip: isSkip,
  });
}

async function getCaptchaImage() {
  const res = await Apis.get_captchaImage({});
  captchaInfo.value = {
    ...res,
    img: res.img ? `data:image/gif;base64,${res.img}` : '',
  };
}

function handleSubmit(params: any, onSuccess?: () => Promise<void> | void) {
  authStore.authLogin(
    {
      username: params.username,
      password: params.password,
      code: captchaInfo.value.code,
      uuid: captchaInfo.value.uuid,
    },
    onSuccess,
  );
}

onMounted(async () => {
  await getCaptchaImage();
});
</script>

<template>
  <div class="w-[90%]">
    <AuthenticationLogin
      :form-schema="formSchema"
      :loading="authStore.loginLoading"
      :show-third-party-login="false"
      :show-code-login="false"
      :show-qrcode-login="false"
      :show-forget-password="false"
      :show-register="false"
      @submit="handleSubmit"
    >
      <template #field3="slotProps">
        <Input placeholder="请输入" v-bind="slotProps" />
      </template>
    </AuthenticationLogin>
  </div>

  <!-- <div v-if="isDev">
    <p class="text-center">快速登录</p>
    <a-space>
      <a-button @click="mockLogin('Admin.itl', 'ABC123')">超级管理员</a-button>
      <a-button @click="mockLogin('zhangxs.itl', 'Rlgs!6243910')">zxs</a-button>
      <a-button @click="mockLogin('zengp.itl', 'Rlgs!6243910')">zp</a-button>
      <a-button @click="mockLogin('rlqym', 'Rlgs!6243910', false)">
        rlqym
      </a-button>
      <a-button @click="mockLogin('rlgxy', 'Rlgs!6243910', false)">
        rlgxy
      </a-button>
    </a-space>
  </div> -->
</template>
